package AlgorithmDesignAndAnalysis.Greedy;

import org.junit.Test;

public class DeleteNumber {


    public String removeKdigits(String num, int k) {
        String sNumber = num;
        int times = k;
        String result = "";
        for (int i = 0; i < sNumber.length()-1; i++) {
            if (times != 0) {
                if (Character.getNumericValue(sNumber.charAt(i)) >= Character.getNumericValue(sNumber.charAt(i + 1))) {
                    times--;
                } else {
                    result += sNumber.charAt(i);
                }
            } else {
                result += sNumber.charAt(i);
            }
        }
        //last nubmer
        result += sNumber.charAt(sNumber.length() - 1);
        if (times != 0) {
            result = result.substring(0, result.length() - times);
        } else {
            if (result.length() != sNumber.length() - k) {
                result += sNumber.substring(k, sNumber.length());
            }
        }
//        System.out.println(result);
        return result.length()==0?"0":result.replaceFirst("^0*","");
    }
}
